package com.android.clinic.app.ui.doctor;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.AppointInfo;
import com.android.clinic.app.entity.DoctorInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.widget.SlideScrollView;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.Utils;
import com.bigkoo.pickerview.TimePickerView;
import com.gyf.barlibrary.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by cheng on 2018/2/7.
 * 医生详情
 */
public class DoctorDetailActivity extends BaseActivity implements SlideScrollView.OnScrollListener {

    private LinearLayout layBasic;

    private int basicLayoutTop;

    private ViewStub labelStub;
    private View detailLine;

    private ImageView ivHead, ivAttention;
    private TextView tvDetailTitle, tvName, tvPosition, tvHospital, tvDomain, tvDescription,
            tvDefaultName, tvDeptName, tvInquirePrice, tvVideoPrice;
    private LinearLayout layDomain, layDescription, layGradationTitle;
    private FrameLayout layDefault;

    private DoctorInfo mDoctorInfo;
    private String doctorId = "";
    private boolean isFirst = false;

    private TimePickerView pvTime;
    private String currentTime = "";
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_doctor_detail;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mImmersionBar.statusBarColorTransform(R.color.colorPrimaryDark)
                .barAlpha(0f)
                .init();

        String reservation = this.getIntent().getStringExtra("reservation");
        String evaluation = this.getIntent().getStringExtra("evaluation");
        doctorId = this.getIntent().getStringExtra("doctorId");

        layBasic = (LinearLayout) findViewById(R.id.layout_basic);
        detailLine = findViewById(R.id.detail_line);
        tvDetailTitle = (TextView) findViewById(R.id.tv_detail_title);
        layGradationTitle = (LinearLayout) findViewById(R.id.layout_gradation_title);
        RelativeLayout layDoctorTop = (RelativeLayout) findViewById(R.id.layout_doctor_top);
        SlideScrollView mScrollView = (SlideScrollView) findViewById(R.id.scrollView);
        mScrollView.setOnScrollListener(this);
        setLayout(layDoctorTop, Utils.getScreenWidth(), DisplayUtil.dip2px(750), DisplayUtil.dip2px(520));
        ImmersionBar.setTitleBar(this, layGradationTitle);

        ivHead = (ImageView) findViewById(R.id.iv_head);
        ivAttention = (ImageView) findViewById(R.id.iv_attention);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvPosition = (TextView) findViewById(R.id.tv_position);
        tvHospital = (TextView) findViewById(R.id.tv_hospital);
        tvDomain = (TextView) findViewById(R.id.tv_domain);
        tvDescription = (TextView) findViewById(R.id.tv_description);
        tvDefaultName = (TextView) findViewById(R.id.tv_default_name);
        tvDeptName = (TextView) findViewById(R.id.tv_dept_name);
        tvInquirePrice = (TextView) findViewById(R.id.tv_inquire_price);
        tvVideoPrice = (TextView) findViewById(R.id.tv_video_price);
        TextView tvReservation = (TextView) findViewById(R.id.tv_reservation);
        TextView tvEvaluation = (TextView) findViewById(R.id.tv_evaluation);
        TextView tvReferral = (TextView) findViewById(R.id.tv_referral);

        tvReservation.setText("服务" + reservation + "人");
        tvEvaluation.setText(evaluation + "条评价");
        tvReferral.setText(String.valueOf((int)(10 + Math.random()*(50 - 10 + 1)) ) + "%复诊率");

        layDomain = (LinearLayout) findViewById(R.id.layout_domain);
        layDescription = (LinearLayout) findViewById(R.id.layout_description);
        layDefault = (FrameLayout) findViewById(R.id.layout_default);

        initVideoReserveTime();
        angoraLogin(ClinicApplication.getUserInfo().getId());
    }

    @Override
    protected void loadData() {
        super.loadData();
        getDoctorDetail();
        getFollow();
    }

    /**
     * 获取医生详情
     */
    private void getDoctorDetail() {
        HttpClient.getHttpService().getDoctorDetail(doctorId)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<DoctorInfo>() {
                    @Override
                    public void onSuccess(DoctorInfo doctorInfo) {
                        mDoctorInfo = doctorInfo;
                        parseDoctorInfo(doctorInfo);
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    /**
     * 获取当前医生是否被关注
     */
    private void getFollow() {
        HttpClient.getHttpService().getFollow(doctorId, ClinicApplication.getUserInfo().getId())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        ivAttention.setImageResource(isFirst ? R.drawable.icon_attention_check
                                : R.drawable.icon_attention_checked);
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    /**
     * 添加关注
     */
    private void addFollow() {
        HttpClient.getHttpService().addFollow(doctorId, ClinicApplication.getUserInfo().getId())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        showToast(isFirst ? "取消关注" : "关注成功");
                        getFollow();
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    /**
     * 解析返回数据并刷新UI
     * @param doctorInfo
     */
    private void parseDoctorInfo(DoctorInfo doctorInfo) {
        if (doctorInfo.getImgUrl().contains(".jpg") && !Utils.isEmpty(doctorInfo.getImgUrl())) {
            ivHead.setVisibility(View.VISIBLE);
            layDefault.setVisibility(View.GONE);
            ImageLoaderUtils.getInstance().loadHeadImage(doctorInfo.getImgUrl(), ivHead);
        } else {
            ivHead.setVisibility(View.GONE);
            layDefault.setVisibility(View.VISIBLE);
            tvDefaultName.setText(doctorInfo.getName());
        }

        tvName.setText(doctorInfo.getName());
        tvPosition.setText(doctorInfo.getPosition());
        tvHospital.setText(doctorInfo.getHospital());
        tvDeptName.setText(doctorInfo.getDeptName());
        tvInquirePrice.setText(Utils.isEmpty(doctorInfo.getInquirePrice()) ? Constants.INQUIRE_PRICE : doctorInfo.getInquirePrice());
        tvVideoPrice.setText(Utils.isEmpty(doctorInfo.getVideoPrice()) ? Constants.VIDEO_PRICE : doctorInfo.getVideoPrice());

        if (!Utils.isEmpty(doctorInfo.getLabel())) {
            if (null == labelStub) {
                labelStub = (ViewStub) findViewById(R.id.label_stub);
                labelStub.inflate();
            } else {
                labelStub.setVisibility(View.VISIBLE);
            }
            String[] labelArray = doctorInfo.getLabel().split(",");
            int labelSize = labelArray.length;
            List<String> labelList = new ArrayList<>();
            for (int i = 0; i < labelSize; i++) {
                labelList.add(labelArray[i]);
            }
            GridView gridLabel = (GridView) findViewById(R.id.grid_label);
            LabelAdapter labelAdapter = new LabelAdapter();
            labelAdapter.addLabel(labelList);
            gridLabel.setAdapter(labelAdapter);
        } else {
            if (null != labelStub) {
                labelStub.setVisibility(View.GONE);
            }
        }

        layDomain.setVisibility(!Utils.isEmpty(doctorInfo.getDomain()) ? View.VISIBLE : View.GONE);
        layDescription.setVisibility(!Utils.isEmpty(doctorInfo.getDescription()) ? View.VISIBLE : View.GONE);
        tvDomain.setText(doctorInfo.getDomain());
        tvDescription.setText(doctorInfo.getDescription());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            basicLayoutTop = layBasic.getTop();
        }
    }

    private class LabelAdapter extends BaseAdapter {

        private List<String> dataList = new ArrayList<>();

        private void addLabel(List<String> data) {
            dataList.addAll(data);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View labelView = LayoutInflater.from(DoctorDetailActivity.this)
                    .inflate(R.layout.item_doctor_detail_label, null);
            TextView tvLabel = (TextView) labelView.findViewById(R.id.tv_detail_label);
            tvLabel.setText(dataList.get(position));
            return labelView;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        //设置标题的背景颜色
        if (scrollY <= 0) {
            layGradationTitle.setBackgroundColor(Color.argb(0, 144, 151, 166));
            mImmersionBar.statusBarDarkFont(true, 0f).init();
            detailLine.setVisibility(View.GONE);
            tvDetailTitle.setText("");
        } //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
        else if (scrollY > 0 && scrollY <= basicLayoutTop / 2) {
            float scale = (float) scrollY / basicLayoutTop;
            float alpha = (255 * scale);
            layGradationTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
            mImmersionBar.statusBarDarkFont(true, 0.2f).init();
            detailLine.setVisibility(View.GONE);
            tvDetailTitle.setText("");
        } else { //滑动到banner下面设置普通颜色
            layGradationTitle.setBackgroundColor(Color.argb(255, 255, 255, 255));
            mImmersionBar.statusBarDarkFont(true, 0.2f).init();
            detailLine.setVisibility(View.VISIBLE);
            tvDetailTitle.setText(mDoctorInfo.getName());
        }

    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            // 图文问诊
            case R.id.btn_graphic_inquiry:
                startActivity(new Intent(this, BuyServiceActivity.class)
                        .putExtra("doctorInfo", mDoctorInfo)
                        .putExtra("inquiryType", "0"));
                break;
            // 视频问诊
            case R.id.btn_advisory:
                pvTime.show(v);
                break;
            // 线下面诊
            case R.id.layout_offline_face_consultation:
                startActivity(new Intent(this, SitDiagnosedActivity.class)
                        .putExtra("doctorInfo", mDoctorInfo));
                break;
            // 医生公告
            case R.id.layout_detail_placard:
                showToast("正常出诊，暂无公告!");
                break;
            case R.id.iv_detail_back:
                finish();
                break;
            // 关注
            case R.id.iv_attention:
                isFirst = !isFirst;
                addFollow();
                break;
            default:break;
        }
    }

    /**
     * 初始化视频预约时间
     */
    private void initVideoReserveTime() {
        Calendar now = Calendar.getInstance();
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH));

        currentTime = getTime(startDate.getTime());

        Calendar endDate = Calendar.getInstance();
        startDate.set(2050, 12, 31);

        //时间选择器
        pvTime = new TimePickerView.Builder(this, (date, v) -> {
            try {
                Date currentDate =  format.parse(currentTime);
                Date selectDate =  format.parse(getTime(date));
                // 使用Date的compareTo()方法，大于、等于、小于分别返回1、0、-1
                if (selectDate.compareTo(currentDate) >= 0) {
                    postVideoAppointing(getTime(date));
                } else {
                    showToast("当前日期不可预约!");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }

    private String getTime(Date date) {
        return format.format(date);
    }

    /**
     * 选择视频预约时间
     * @param time
     */
    private void postVideoAppointing(String time) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoTime", time);
            jsonObject.put("doctorId", mDoctorInfo.getId());
            jsonObject.put("userId", ClinicApplication.getUserInfo().getId());
            jsonObject.put("deptId", mDoctorInfo.getDeptId());
            jsonObject.put("deptName", mDoctorInfo.getDeptName());
            jsonObject.put("hospitalId", mDoctorInfo.getHospitalId());
            jsonObject.put("hospitalName", mDoctorInfo.getHospitalName());

            MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(jsonType, jsonObject.toString());
            HttpClient.getHttpService().postAppoint(Constants.VIDEO_APPOINT_URL, body).compose(this.bindToLifecycle())
                    .compose(RxObservableUtils.applySchedulers())
                    .subscribe(new BaseObserver<AppointInfo>() {
                        @Override
                        public void onSuccess(AppointInfo appointInfo) {
                            Intent intent = new Intent(DoctorDetailActivity.this, BuyServiceActivity.class);
                            intent.putExtra("doctorInfo", mDoctorInfo);
                            intent.putExtra("appointId", appointInfo.getId());
                            intent.putExtra("inquiryType", "1");
                            startActivity(intent);
                        }

                        @Override
                        public void onFailure(String message) {
                            showToast(message);
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
